package com.amox.uitest.adapter;

import java.util.List;

import org.dom4j.Element;

import com.amox.uitest.common.KeyWord;
import com.amox.uitest.common.ReturnException;
import com.amox.uitest.kit.LogKit;
import com.amox.uitest.kit.StrKit;
import com.amox.uitest.tcase.BaseTestCase;

public abstract class BaseAdapter<T> {
	
	protected BaseTestCase uitest;
	
	public BaseAdapter(BaseTestCase uitest) {
		this.uitest = uitest;
	}

	/**
	 * cmd node switch adapter
	 * @return
	 */
	public abstract T adapter(Element element) throws Exception;
	
	public T play(Element element) throws Exception {
		if(null == element) {
			return null;
		}
		LogKit.printLog("Running Command : " + element.getName());
		T t = this.adapter(element);
		return t;
	}
	
	/**
	 * children element
	 * @param element
	 * @param elemList
	 * @throws Exception 
	 */
	protected boolean execElement(Element element) throws Exception {
		String targetName = new StringBuffer(BaseAdapter.class.getPackage().getName())
				.append("." + StrKit.me().upperFirst(element.getName()))
				.append("Adapter")
				.toString();
		
		BaseAdapter<?> adpater = (BaseAdapter<?>) Class.forName(targetName)
				.getConstructor(BaseTestCase.class)
				.newInstance(uitest);
		
		boolean rt = (Boolean)adpater.play(element);
		if(KeyWord.resault.toString().equals(element.getName())) {
			// return
			throw new ReturnException(rt);
//			return rt;
		}
		
		List<Element> elements = element.elements();
		if (elements.size() > 0) {
			if(!rt) { // isFalse
				return true;
			}
			for (Element sub : elements) {
				execElement(sub);
			}
		}
		
		return rt;
	}
}
